<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>音乐播放器</title>
    <style>
        canvas {
            display: block;
            margin: 20px auto;
            border: 2px solid #333;
        }
    </style>
</head>
<body>
    <!-- 音频元素 -->
    <audio id="audio" controls>
        <source src="../img/Rodrigo y Gabriela - Fram.mp3" type="audio/mp3">
        Your browser does not support the audio element.
    </audio>
    <!-- 用于绘制律动效果的Canvas元素 -->
    <canvas id="visualizer" width="100" height="600"></canvas>

    <script>
        // 页面加载后执行初始化
        window.addEventListener('load', init, false);

        function init() {
            // 获取音频元素和上下文
            var audio = document.getElementById('audio');
            var audioContext = new (window.AudioContext || window.webkitAudioContext)();
            var analyser = audioContext.createAnalyser();
            var source = audioContext.createMediaElementSource(audio);

            // 连接音频源和分析器
            source.connect(analyser);
            analyser.connect(audioContext.destination);

            // 设置分析器参数
            analyser.fftSize = 256;
            var bufferLength = analyser.frequencyBinCount;
            var dataArray = new Uint8Array(bufferLength);

            // 获取canvas元素和上下文
            var canvas = document.getElementById('visualizer');
            var canvasContext = canvas.getContext('2d');

            // 绘制律动效果
            function draw() {
                analyser.getByteFrequencyData(dataArray);

                canvasContext.fillStyle = 'rgb(0, 0, 0)';
                canvasContext.fillRect(0, 0, canvas.width, canvas.height);

                var barWidth = (canvas.width / bufferLength) * 2;
                var barHeight;
                var x = 0;

                for (var i = 0; i < bufferLength; i++) {
                    barHeight = dataArray[i] / 0.42;

                    // 根据频率数据设置颜色和绘制矩形
                    canvasContext.fillStyle = 'rgb(' + (barHeight + 100) + ',50,50)';
                    canvasContext.fillRect(x, canvas.height - barHeight, barWidth, barHeight);

                    x += barWidth + 1;
                }

                // 递归调用绘制函数，形成动画效果
                requestAnimationFrame(draw);
            }

            // 播放音频时启动绘制律动效果
            audio.addEventListener('play', function () {
                // 在播放时，需要先调用audioContext的resume方法
                audioContext.resume().then(function () {
                    // 启动绘制函数
                    draw();
                });
            });
        }
    </script>
</body>
</html>
